package common.plugins.pay;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.orhanobut.logger.Logger;
import com.tekj.cxqcb.config.enums.EventBusMsgBean;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;

import es.dmoral.toasty.Toasty;

import static com.tekj.cxqcb.config.enums.EventBusMsgBean.EnumStatus.支付宝支付成功;


/**
 * description: 获取支付宝支付参数，并调起微信支付
 * autour: tongzhenggang@126.com
 * date: 2017/8/9
 */
public class GetAlipayParameter {
    private int UserId = 0;//MainFragmentActivity.mainBean.getData().getId();
    private Activity mActivity;
    private String orderInfo = "";

    /**
     * 支付宝支付回调
     */
    private static final int SDK_PAY_FLAG = 1;


    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);

//                    Toast.makeText(getApplicationContext(), payResult.toString(), Toast.LENGTH_LONG).show();

                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&docType=1)
                     * 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    Logger.d("resultStatus>>>" + resultStatus);
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
//                        ToastUtil.show(mActivity, "支付成功");
                        Toasty.success(mActivity, "支付成功").show();
//                        mActivity.finish();
                        EventBus.getDefault().post(new EventBusMsgBean(支付宝支付成功, "finish"));

                    } else {

                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
//                            ToastUtil.show(mActivity, "支付结果确认中");
                            Toasty.info(mActivity, "支付结果确认中").show();
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
//                            ToastUtil.show(mActivity, "支付失败");
                            Toasty.error(mActivity, "支付失败").show();
                        }
                    }


                    break;
                }
                default:
                    break;
            }
        }

    };

    /**
     * 文档：https://docs.open.alipay.com/204/105296/
     * 获取支付宝支付接口参数，并调起支付
     * new GetAlipayParameter(mActivity, orderNo);
     */
    public GetAlipayParameter(final Activity activity, String data) {
        this.mActivity = activity;

        final String orderInfo = data;// "alipay_sdk=alipay-sdk-php-20161101&app_id=2018022602277613&biz_content=%7B%22body%22%3A%22%5Cu652f%5Cu4ed8%5Cu8d2d%5Cu4f73%5Cu5353%5Cu5b9d%5Cu5546%5Cu5e73%5Cu53f0%5Cu5546%5Cu54c1%5Cu8d39%5Cu7528100%5Cu5143%5Cuff0c%5Cu8ba2%5Cu5355%5Cu53f7%5Cuff1aDL201803097654526%22%2C%22subject%22%3A%22%5Cu652f%5Cu4ed8%5Cu8d2d%5Cu4e70%5Cu5546%5Cu54c1%5Cu8d39%5Cu7528100%5Cu5143%22%2C%22out_trade_no%22%3A%22DL201803097654526%22%2C%22timeout_express%22%3A%221d%22%2C%22total_amount%22%3A100%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%7D&charset=UTF-8&format=JSON&method=alipay.trade.app.pay&notify_url=http%3A%2F%2Fyouxibang.zjr1.com%2F%2Fapi%2Falipay%2FAliPayNotify.html&sign_type=RSA2&timestamp=2018-03-09+09%3A51%3A42&version=1.0&sign=7Wt%2FiveptXJLQHXLpvYLolUNke7WN3CYJIDFC1V4JBStCE7PhFQqYvtjVPJ1KlnV6mtpRAosgPVxsGUKEMQn5Lwb4gw4%2FpjBX0OgXfvFdkWMOvlxENsiLZYamd0RWOf03JH%2BWv32TsiL3SPhZT2k4bvceQewDTDHCvaiZBextVnJUCCOfc%2FFBeTA78Ybw54kvbDbntV9iCGf7QDRIqViJSFnz6A%2F4yj8b1mqpSTPSLwsGZJSOCY3Da7KT3l3IP1qreWh%2Bnhy5oFme54dH9rjjC7aMMA%2F9Qh4J4UjJ5aJ4fE4kWANo74eB4WP4lZ2gNmBsWjpZiTNWHgqDhAn6r6foA%3D%3D";
        Runnable r = new Runnable() {
            @Override
            public void run() {
                PayTask payTask = new PayTask(mActivity);

                Object result = payTask.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        new Thread(r).start();


    }
}
